package com.sczmgk.hotline_pzh.DesJson;

import com.sczmgk.hotline_pzh.constants.Constants;

import org.apache.commons.codec.digest.DigestUtils;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;

public class Des3 {

	public static void main(String[] args) throws Exception {

	}

	/**
	 * ECB加密,不要IV
	 * 
	 * @param key
	 *            密钥
	 * 
	 * @param data
	 *            明文
	 * 
	 * @return Base64 编码的密文
	 */
	public static String des3EncodeECB(String key, String data) {
		String encode = "";
		if (isEmpty(data)) {
			return null;
		}
		try {
			byte[] db = data.getBytes("UTF-8");
			byte[] kb = key.getBytes("UTF-8");
			Key deskey = null;
			DESedeKeySpec spec = new DESedeKeySpec(kb);
			SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
			deskey = keyfactory.generateSecret(spec);
			Cipher cipher = Cipher.getInstance("desede" + "/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, deskey);
			byte[] bOut = cipher.doFinal(db);
			encode = Base64.encodeToString(bOut, Base64.NO_WRAP).trim();// 自定义
			return encode;
		} catch (Exception e) {
		}
		return encode;
	}

	/**
	 * ECB解密,不要IV
	 * 
	 * @param key
	 *            密钥
	 * @param data
	 *            Base64编码的密文
	 * @return 明文
	 * @throws Exception
	 */
	public static String des3DecodeECB(String key, String data)
			 {
		String decodeStr = "";
		if (isEmpty(data)) {
			return null;
		}
		try {
			byte[] kb = key.getBytes("UTF-8");
			Key deskey = null;
			byte[] decode = Base64.decode(data, Base64.NO_WRAP);
			DESedeKeySpec spec = new DESedeKeySpec(kb);
			SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
			deskey = keyfactory.generateSecret(spec);
			Cipher cipher = Cipher.getInstance("desede" + "/ECB/PKCS5Padding");
			cipher.init(Cipher.DECRYPT_MODE, deskey);
			byte[] bOut = cipher.doFinal(decode);
			decodeStr = new String(bOut, "utf-8");
		} catch (Exception e) {
		}
	return decodeStr;
	}

	/**
	 * 是否为空
	 * 
	 * @param value
	 * @return
	 */
	public static boolean isEmpty(String value) {
		if (value == null || value.length() == 0 || "null".equals(value)) {
			return true;
		} else
			return false;
	}

	public static String getEncodePWD(String pwd){
		String des3Str = Des3.des3EncodeECB(Constants.SERVICE_PUBLIC_KEY, pwd);
		return DigestUtils.md5Hex(des3Str);
	}
}
